using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class LoginOrRegister : MonoBehaviour {
	
	public UILabel userNameText;
	
	string url = "http://";
	string userName;
	
	// Use this for initialization
	void Start () {
		//TODO
		//MaxLengthNumber of Name
	}

	//Click createRole Button
	void OnClick(){
		if(!ValidationCheck()){
			return;
		}
		
		StartCoroutine(Get(url));
	}
	
	bool ValidationCheck(){
		//has Sensitive Words or not
		//if(has Sensitive Words){
		//	return false;
		//}
		
		//String's Length check
		if(userName.Length > 8 || userName.Length < 4){
			Debug.Log("Username should be between 4 and 8;");
			//TODO
			return false;
		}
		
		string RegexTest = "^([\u4e00-\u9fa5]+|[a-zA-Z0-9]+)$";
		
		if(!Regex.IsMatch(userName,RegexTest)){
			Debug.Log("Username is English,Chinese or Numeber");
			//TOOD
			return false;
		}
		
		
		return true;
	}
	
	public void LoginPressed(){
		//
        Dictionary<string,string> dictionary = new Dictionary<string, string> ();
        //
        dictionary.Add("action","0");
        dictionary.Add("usrname","xys");
        dictionary.Add("psw","123456");
 
        StartCoroutine(Post("http://192.168.1.12/login.php",dictionary));
	}
	
	public void RegisterPressed(){
		//
        Dictionary<string,string> dictionary = new Dictionary<string, string> ();
        dictionary.Add("action","1");
        dictionary.Add("usrname","xys");
        dictionary.Add("psw","123456");
 
        StartCoroutine(Post("http://192.168.1.12/login.php",dictionary));
	}
	
	//
    IEnumerator Post(string url, Dictionary<string,string> post)
    {
        WWWForm form = new WWWForm();
        foreach(KeyValuePair<string,string> post_arg in post){
            form.AddField(post_arg.Key, post_arg.Value);
        }
 
        WWW www = new WWW(url, form);
        yield return www;
 
        if (www.error != null){
            //
            Debug.Log("error is :"+ www.error);
        }else{
            //
             Debug.Log("request ok : " + www.text);
        }
    }
	
	IEnumerator Get(string url){
        WWW www = new WWW (url);
        yield return www;
 
        if (www.error != null){
            //Get is failed
            Debug.Log("error is :"+ www.error);
        }else{
            //GET is successful
            Debug.Log("request ok : " + www.text);
        }
    }
}
